<template>
  <div>
    <el-cascader
      @change="changeCascader"
      :props="state.props"
      :options="state.options"
      placeholder="设置标准即选择设备"
      clearable
      v-model="state.groupIds"
      disabled
    />
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, reactive, inject } from "vue";
import type { TableColumn, TableRow, OptButton } from "@/utils/baTable"; //表格列行类型
import { useStandard } from "@/store/backend/LineCruiseM/standard";
import type { CascaderProps } from "element-plus";

const standard = useStandard();

interface Props {
  renderValue: any; // 单元格值
  renderRow: TableRow; // 当前行数据
  renderField: TableColumn; // 当前列数据
}

const state: { props: CascaderProps; options: anyObj[]; groupIds: any[] } =
  reactive({
    props: {
      multiple: true,
    },
    options: [],
    groupIds: [],
  });

//选择标准 并将设备基础信息保存
const changeCascader = (value: any) => {
  if (JSON.stringify(value) === "[]") {
    //为空就删除equipmentInfos对应的数据
    dealEquipmentInfos(standard.equipmentInfos, [], false);
  } else {
    let groupIds = [...new Set(value.flat(Infinity))];
    // console.log("标准级联选择器", value, props.renderRow, groupIds);
    dealEquipmentInfos(standard.equipmentInfos, groupIds, true);
  }
};

//处理equipmentInfos数组数据
const dealEquipmentInfos = (data: any[], groupIds: any[], boo: boolean) => {
  let activeIndex = data.findIndex((value: any, index: any, arr: any) => {
    console.log("findIndex", value, index, arr, props.renderRow);
    return value.ecode === props.renderRow.code;
  });
  console.log("activeIndex", activeIndex);
  if (boo) {
    if (activeIndex == -1) {
      let { code, name, gatewaycode, addr, cname } = props.renderRow;
      //无该数据即为新增
      standard.equipmentInfos.push({
        ecode: code,
        ename: name,
        gatewaycode,
        address: addr,
        groupIds,
      });
    } else {
      //即为修改该数据的groupIds
      standard.equipmentInfos[activeIndex].groupIds = groupIds;
    }
  } else {
    console.log("删除");
    //查找该设备数据并删除
    standard.equipmentInfos.splice(activeIndex, 1);
  }
};

const props = withDefaults(defineProps<Props>(), {});

//反显标准id
const showGroupIds = () => {
  let i = standard.equipmentInfos.findIndex(
    (value: any, index: any, arr: any) => {
      return value.ecode === props.renderRow.code;
    }
  );
  if (i !== -1) {
    state.groupIds = standard.equipmentInfos[i].groupIds;
  }
};

onMounted(() => {
  state.options = standard.options; //巡检标准数据
  console.log(
    "单元格值",
    props.renderRow,
    standard.options,
    standard.equipmentInfos
  );
  showGroupIds();
});
</script>
<style lang="scss" scoped></style>
